#include <vector>
#include<unordered_map>
class Solution {
public:
    
    int longestWPI(std::vector<int>& hours) {
        int len = hours.size();
        std::unordered_map<int, int> map;
        map.insert({0,-1});
        int sum = 0;
        int ans = 0;
        
        for (int i = 0; i < len; i++)
        {
            sum+= hours[i] >8 ?1:-1;
            if (sum >0)
            {
                ans =i +1;
            }else
            {
                if (map.find(sum-1)!=map.end())
                {
                    ans = std::max(ans,i-map[sum-1]);
                }
                
            }
            if (map.find(sum)==map.end())
            {
                map.insert({sum,i});
            }
        }
        return ans;
    }
};